from sqlalchemy import BigInteger, Column, Integer, create_engine, func,DateTime,String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from app.core.snowflake import snowflake
from app.core.config import settings
from contextlib import contextmanager

engine = create_engine(settings.SQLITE_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Basic = declarative_base()

class Base(Basic):
    __abstract__ = True  # 声明为抽象基类
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    id = Column(BigInteger, primary_key=True, default=snowflake.generate)

class Business(Base):
    __abstract__ = True  # 声明为抽象基类
    code = Column(String(255))
    name = Column(String(255))
    remark = Column(String(255))

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@contextmanager
def get_db_context():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()